<script setup lang="ts">
import {
  ercAlarmCountStat,
  getCategoryEmissionYoy,
  getFactoryEmission,
  queryManoeuvreAndERT,
  queryQtyLine,
  query_6,
  taskCount
} from "@/api/leadScreenNew";
import { isHasPermission } from "@/utils/auth";
import { debounce } from "@pureadmin/utils";
import dayjs from "dayjs";
import * as echarts from "echarts";
import { computed, nextTick, onMounted, onUnmounted, ref } from "vue";
import BarChart from "./Bar.vue";
import Carousel from "./Carousel.vue";
import CarouselItem from "./CarouselItem.vue";
import Guage from "./Guage.vue";
import LineStack from "./LineStackChart.vue";
import LittlePie from "./LittlePie.vue";
import Title from "./Title.vue";
import { usePolling } from "./hooks";
const total = ref<string | number>(0);
const pieChartRef = ref();
const emission = ref();
const charts = ref([]);
const HSERef = ref();
const color = ["#0795CC", "#12A5BB", "#0CAE9A", "#57B36D", "#3CC49B", "#72C781", "#9DC66C", "#C5C360"];
const EMISSION_YOY = [
  {
    name: "类别一",
    ratio: 93.5,
    value: 908.22,
    yoy: null
  },
  {
    name: "类别二",
    ratio: 6.5,
    value: 22726.73,
    yoy: null
  },
  {
    name: "类别三",
    ratio: 6.5,
    value: 92.14,
    yoy: null
  },
  {
    name: "类别四",
    ratio: 6.5,
    value: 24721.63,
    yoy: null
  }
];
// 初始化碳排放
let pieChart = null;
const initPieChart = async () => {
  if (!pieChartRef.value) {
    return;
  }
  const year = new Date().getFullYear() + "";

  // 1、数据请求
  // if (!isHasPermission("EQUIP_REAL_DATA")) {
  //   const data = EMISSION_YOY.map(item => item.value).reduce((pre, cur) => {
  //     return pre + cur;
  //   });
  //   total.value = data.toLocaleString();
  //   emission.value = EMISSION_YOY.map(item => ({ ...item, name: item.name ? item.name.split(" ")[0] : "-" }));
  // } else {
  const facList = JSON.parse(localStorage.getItem("facList"));
  const facCode = localStorage.getItem("facCode");
  const facItem = facList.find(item => item.code === facCode);
  const templateData = await query_6({ templateName: "ISO14064", templateStatus: "启用" });
  const target = templateData?.data?.find(item => item.templateName === "ISO14064");
  if (!target) {
    console.error("未查询到模板ISO14064");
    return;
  }
  const [{ value: data }, { value: emissionData }] = await Promise.allSettled([
    getFactoryEmission({
      startDate: `${year}-01-01 00:00:00`,
      endDate: `${year}-12-31 23:59:59`,
      level: facItem.name,
      dimension: "Y",
      // templateName: "ISO14064"
      templateId: target.id
    }),
    getCategoryEmissionYoy({
      startDate: `${year}-01-01 00:00:00`,
      endDate: `${year}-12-31 23:59:59`,
      level: facItem.name,
      dimension: "Y",
      // templateName: "ISO14064"
      templateId: target.id
    })
  ]);
  total.value = (data as any)?.total?.toLocaleString() || 0;
  emission.value = emissionData?.map(item => ({ ...item, name: item.name ? item.name.split(" ")[0] : "-" }));
  // 2、图表渲染
  let option;
  const chartDom = pieChartRef.value;
  if (!pieChart) {
    pieChart = echarts.init(chartDom, null, { renderer: "svg" });
  }
  option = {
    tooltip: {
      trigger: "item",
      position: "right",
      appendTo: () => HSERef.value,
      formatter: function (params) {
        const { name, data, color } = params;
        return `<div style="display:flex;align-items:center;">
            <div style="width: 10px;height: 10px;border-radius:50%;background: ${color};margin-right:3px;"></div>
            <div style="color: rgba(255,255,255,0.9);line-height: 18px;margin-right:12px">${name}</div>
            <div  style="color: rgba(255,255,255,0.9);line-height: 18px;font-weight: 600;">${data.ratio}%</div>
          </div>`;
      },
      borderColor: "transparent",
      backgroundColor: "rgba(9,28,59,0.8)",
      padding: [3, 8],
      textStyle: {
        fontSize: 12
      },
      extraCssText:
        "box-shadow: 0px 5px 5px -3px rgba(0,0,0,0.1), 0px 8px 10px 1px rgba(0,0,0,0.06), 0px 3px 14px 2px rgba(0,0,0,0.05);border-radius: 3px;backdrop-filter: blur(1px);"
    },
    devicePixelRatio: window.devicePixelRatio || 2,
    grid: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    },
    legend: {
      show: false
    },
    color,
    series: [
      {
        name: "今日任务",
        type: "pie",
        radius: ["60%", "82%"],
        avoidLabelOverlap: false,
        padAngle: 0,
        itemStyle: {
          borderRadius: 0,
          color: "#fff"
        },
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          disabled: true
        },
        labelLine: {
          show: false
        },
        tooltip: { show: false },
        data: [{ value: 1 }]
      }, // 白色背景

      {
        name: "今日任务",
        type: "pie",
        radius: ["60%", "82%"],
        avoidLabelOverlap: false,
        padAngle: 1,
        itemStyle: {
          borderRadius: 0
        },
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          label: {
            show: false,
            fontSize: 14,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: emission.value
      }
    ]
  };
  option && pieChart.setOption(option);
  if (!charts.value.includes(pieChart)) {
    charts.value.push(pieChart);
  }
};
// 初始化ERC
const ercData = ref();
const initErcChart = async () => {
  const year = new Date().getFullYear() + "";
  const data = await queryManoeuvreAndERT({ trendTime: year });
  ercData.value = data;
};
// 初始化消防
const HSEData = ref();
const initHSEData = async () => {
  const data = await taskCount();
  HSEData.value = data;
};
const alertTotal = ref(0);
const alertData = ref();
const initAlertData = async () => {
  const data = await ercAlarmCountStat();
  alertData.value = data;
  let total = 0;
  Object.values(data).forEach(element => {
    total += element;
  });
  alertTotal.value = total;
};
const checkRatio = computed(() => {
  if (HSEData.value) {
    const {
      checkTaskCount: { done, total }
    } = HSEData.value;
    const ratio = total ? ((done / total) * 100).toFixed(0) : 100;
    return ratio;
  }
  return 0;
});
const workorderRatio = computed(() => {
  if (HSEData.value) {
    const {
      workOrderCount: { done, total }
    } = HSEData.value;
    const ratio = total ? ((done / total) * 100).toFixed(0) : 100;
    return ratio;
  }
  return 0;
});
const getData = key => {
  const value = alertData.value[key];
  if (!value) {
    return [{ value: value }, { value: 1 }];
  }
  return [{ value: value }, { value: alertTotal.value ? alertTotal.value - value : 0 }];
};
// 初始化能耗
const NHData = ref();
const initNHData = async () => {
  let now = new Date();
  let tenDaysAgo = new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000); // 1天 = 24 * 60 * 60 * 1000 毫秒
  let oneDaysAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000); // 1天 = 24 * 60 * 60 * 1000 毫秒
  const YearStartTime = dayjs().format("YYYY-01-01");
  const endtTime = dayjs(oneDaysAgo).format("YYYY-MM-DD");
  const daysStartTime = dayjs(tenDaysAgo).format("YYYY-MM-DD");
  const qtyParams = {
    dimension: "YEAR",
    startDate: YearStartTime,
    endDate: endtTime,
    kind: ["electricity", "running", "reclaim", "upw", "steam", "hot", "ng", "cda", "n2", "ar", "o2", "he", "h2", "co2"]
  };
  const zbmParams = {
    dimension: "DAY",
    startDate: daysStartTime,
    endDate: endtTime,
    kind: ["electricity", "running", "reclaim", "upw", "steam", "hot", "ng", "cda", "n2", "ar", "o2", "he", "h2", "co2"]
  };
  const data = await Promise.all([queryQtyLine(qtyParams), queryQtyLine(zbmParams)]);
  NHData.value = data;
};
const barDataConfig = [
  {
    name: "电",
    type: ["electricity"],
    color: [["rgba(30,121,255,0.4)", "#1E79FF"]],
    nameObj: {
      electricity: "电"
    }
  },
  {
    name: "天然气",
    type: ["ng"],
    color: [["rgba(30,121,255,0.4)", "#1E79FF"]],
    nameObj: {
      ng: "天然气"
    }
  },
  {
    name: "蒸汽/热水",
    type: ["steam", "hot"],
    color: [
      ["rgba(11,180,213,0.4)", "#0BB4D5"],
      ["rgba(30,121,255,0.4)", "#1E79FF"]
    ],
    nameObj: {
      steam: "蒸汽",
      hot: "热水"
    }
  }
];
const barData = computed(() => {
  if (!NHData.value) {
    return;
  }
  const data = NHData.value[1];
  const arr = barDataConfig.map(item => {
    const { yaxis = [], xaxis = [] } = data.line;
    const itemData = yaxis
      .filter(chartData => item.type.includes(chartData.name))
      .map(chartData => {
        if (!isHasPermission("EQUIP_REAL_DATA")) {
          if (chartData.name === "ng") {
            return {
              ...chartData,
              nameDesc: item.nameObj[chartData.name],
              value: "590、599、605、601、612、603、595、607、601、605".split("、")
            };
          }

          if (chartData.name === "steam") {
            return {
              ...chartData,
              nameDesc: item.nameObj[chartData.name],
              value: "265.73、238.05、282.34、271.26、210.37、215.90、238.05、249.12、257.42、235.28".split("、")
            };
          }
          return {
            ...chartData,
            nameDesc: item.nameObj[chartData.name]
          };
        } else {
          return {
            ...chartData,
            nameDesc: item.nameObj[chartData.name]
          };
        }
      });
    return {
      ...item,
      unit: itemData[0].unit,
      data: itemData,
      xaxis: xaxis.map(item => dayjs(item).format("MM/DD"))
    };
  });
  return arr;
});
const lineDataConfig = [
  {
    name: "水",
    type: ["running", "reclaim", "upw"],
    nameObj: {
      running: "自来水",
      reclaim: "再生水",
      upw: "超纯水"
    }
  },
  {
    name: "大宗气",
    type: ["cda", "n2"],
    nameObj: {
      cda: "CDA",
      n2: "N₂"
    }
  },
  {
    name: "大宗气",
    type: ["ar", "o2", "he", "h2", "co2"],
    nameObj: {
      ar: "AR",
      o2: "O₂",
      he: "HE",
      h2: "H₂",
      co2: "CO₂"
    }
  }
];
const lineData = computed(() => {
  if (!NHData.value) {
    return;
  }
  const data = NHData.value[1];
  const arr = lineDataConfig.map(item => {
    const { yaxis = [], xaxis = [] } = data.line;
    const itemData = yaxis
      .filter(chartData => item.type.includes(chartData.name))
      .map(chartData => ({
        ...chartData,
        nameDesc: item.nameObj[chartData.name]
      }));
    return {
      ...item,
      unit: itemData[0].unit,
      data: itemData,
      xaxis: xaxis.map(item => dayjs(item).format("MM/DD"))
    };
  });
  return arr;
});
// 处理窗口大小变化
const handleResize = debounce(() => {
  // 图表
  charts.value.forEach(chart => {
    chart.resize();
  });
}, 60);
const init = () => {
  nextTick(() => {
    initPieChart();
    initErcChart();
    initHSEData();
    initAlertData();
    initNHData();
  });
};
// 轮询
usePolling(
  () => {
    initPieChart();
    initErcChart();
    initHSEData();
    initNHData();
  },
  {
    pollingInterval: 10 * 60 * 1000
  }
);
usePolling(
  () => {
    initAlertData();
  },
  {
    pollingInterval: 30 * 1000
  }
);
onMounted(() => {
  init();
  window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  charts.value.forEach(chart => {
    chart.dispose();
  });
});
</script>
<template>
  <section>
    <px-row :gutter="8">
      <!-- HSE -->
      <px-col :span="12" class="screen-card-box">
        <div class="card-content" ref="HSERef">
          <div class="card-title">HSE</div>
          <px-row>
            <px-col :span="8">
              <Title title="碳排放" />
              <div class="flex-row mt-10">
                <!-- 环形图 -->
                <div class="pie-chart-box">
                  <div class="circle" v-show="emission?.length > 0">
                    <div class="circle-title">碳排放总量</div>
                    <div class="circle-num">{{ total }}</div>
                    <div class="circle-unit">tCO₂e</div>
                  </div>
                  <div class="pie-chart" ref="pieChartRef"></div>
                </div>
                <!-- 滚动列表 -->
                <px-scrollbar class="scroll-container">
                  <div v-for="(item, index) in emission" :key="index" class="item">
                    <div class="dot" :style="`background:${color[index % 8]}`"></div>
                    <div class="flex-grow item-content">
                      <div class="item-detail">
                        <px-text class="item-name" truncated>{{ item.name }}</px-text>
                      </div>
                      <div class="item-detail">
                        <span class="item-value">{{ Number(item.value).toLocaleString() }}</span
                        ><sub class="item-unit">tCO₂e</sub>
                      </div>
                    </div>
                  </div>
                </px-scrollbar>
              </div>
            </px-col>
            <div class="erc-line ml-9"></div>
            <px-col :span="8">
              <Title title="ERC" />
              <div class="flex-row mt-10">
                <px-row class="erc-item-box flex-row">
                  <px-col :span="12" class="erc-item">
                    <div class="erc-item-name">演习完成率</div>
                    <Guage v-if="ercData" :data="{ value: ercData.manoeuvre || '0%' }" />
                  </px-col>
                  <px-col :span="12" class="erc-item">
                    <div class="erc-item-name">ERT参演率</div>
                    <Guage v-if="ercData" :data="{ value: ercData.cultivate || '0%' }" />
                  </px-col>
                </px-row>
              </div>
            </px-col>
            <div class="erc-line mr-9"></div>
            <px-col :span="8">
              <Title class="mb-12" title="消防" />
              <px-row class="mb-4">
                <px-col :span="12">
                  <div class="hse-item-name">月度巡检工单</div>
                  <div class="hse-item-name">完成率</div>
                  <div class="hse-item-num">
                    <span>{{ checkRatio }}%</span>
                  </div>
                </px-col>
                <px-col :span="12">
                  <div class="hse-item-name">月度维修工单</div>
                  <div class="hse-item-name">完成率</div>
                  <div class="hse-item-num">
                    <span>{{ workorderRatio }}%</span>
                  </div>
                </px-col>
              </px-row>
              <px-row v-if="alertData">
                <px-col :span="8">
                  <div class="hse-item-name">火警</div>
                  <LittlePie :data="getData('FIRE')" :color="['#9261CF', '#2D447D']" />
                </px-col>
                <px-col :span="8">
                  <div class="hse-item-name">监管</div>
                  <LittlePie :data="getData('SUPERVISE')" :color="['#9D7707', '#2D447D']"
                /></px-col>
                <px-col :span="8">
                  <div class="hse-item-name">故障</div>
                  <LittlePie :data="getData('FAULT')" :color="['#C84D54', '#2D447D']"
                /></px-col>
              </px-row>
            </px-col>
          </px-row>
        </div>
      </px-col>
      <!-- 能源耗量监控 -->
      <px-col :span="12" class="screen-card-box">
        <div class="card-content">
          <div class="card-title">能源耗量监控</div>
          <ul class="flex nh-header">
            <li class="flex mr-45">
              <div class="zbm"></div>
              <div class="jk-text">
                当年累计折标煤<span class="jk-num" v-if="NHData">{{ NHData[0]?.scoal?.toLocaleString() }}</span
                ><sub class="jk-unit">tce</sub>
              </div>
            </li>
            <li class="flex">
              <div class="nh"></div>
              <div class="jk-text">
                当年能耗费用累计<span class="jk-num" v-if="NHData">{{ (NHData[0].amt / 10000).toFixed(0) }}</span
                ><sub class="jk-unit">万元</sub>
              </div>
            </li>
          </ul>
          <Carousel height="16vh">
            <CarouselItem>
              <px-row v-if="barData">
                <px-col :span="8" v-for="(item, index) in barData" :key="index">
                  <Title :title="item.name" />
                  <BarChart :data="item" />
                </px-col>
              </px-row>
            </CarouselItem>
            <CarouselItem>
              <px-row v-if="lineData">
                <px-col :span="8" v-for="(item, index) in lineData" :key="index">
                  <Title :title="item.name" />
                  <LineStack :data="item" />
                </px-col>
              </px-row>
            </CarouselItem>
          </Carousel>
        </div>
      </px-col>
    </px-row>
  </section>
</template>
<style lang="scss" scoped>
@import url("../card.scss");
:deep(.px-row) {
  flex-wrap: nowrap;
  .px-col {
    flex-shrink: 1;
  }
}

.screen-card-box {
  height: 242rpx;
}
.mt-10 {
  margin-top: 10rpx;
}
.ml-9 {
  margin-left: 17rpx;
}
.mr-9 {
  margin-right: 17rpx;
}
.mb-12 {
  margin-bottom: 12rpx;
}
.mb-4 {
  margin-bottom: 4rpx;
}
.pie-chart-box {
  width: 142rpx;
  height: 142rpx;
  flex-shrink: 0;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  .circle {
    width: 78rpx;
    height: 78rpx;
    box-shadow: inset 0px 0px 18px 0px #00a9d7;
    border: 1px solid #73de8d;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    z-index: 10;
    &-title {
      font-size: 10rpx;
      font-family: AlibabaPuHuiTi-Regular, AlibabaPuHuiTi;
      font-weight: 400;
      color: rgba(255, 255, 255, 0.9);
      line-height: 16rpx;
      margin-bottom: 5rpx;
    }
    &-num {
      font-size: 16rpx;
      font-family: AlibabaPuHuiTiM;
      color: rgba(255, 255, 255, 0.9);
      line-height: 18rpx;
      margin-bottom: 2rpx;
    }
    &-unit {
      font-size: 10px;
      font-family: AlibabaPuHuiTi-Regular, AlibabaPuHuiTi;
      font-weight: 400;
      color: rgba(255, 255, 255, 0.6);
      line-height: 16px;
    }
  }
}
.pie-chart {
  width: 100%;
  height: 142rpx;
  position: absolute;
  top: 0;
  left: 0;
}
.flex-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.scroll-container {
  width: 138rpx;
  height: 168rpx;
  overflow: hidden;
  .item {
    width: 100%;
    height: 42rpx;
    background: rgba(3, 10, 26, 0.1);
    padding: 3rpx 12rpx;
    display: flex;
    align-items: center;
    overflow: hidden;
    &:nth-child(even) {
      background: rgba(94, 144, 255, 0.1);
    }
    .dot {
      width: 10rpx;
      height: 10rpx;
      flex-shrink: 0;
      margin-right: 8rpx;
      border-radius: 50%;
    }
    .flex-grow {
      flex-grow: 1;
    }
    .item-content {
      width: 70rpx;
    }
  }
  .item-name {
    font-size: 12rpx;
    font-family: AlibabaPuHuiTi-Regular, AlibabaPuHuiTi;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.9);
    line-height: 1;
  }
  .item-detail {
    line-height: 1;
  }
  .item-value {
    font-size: 12rpx;
    font-family: AlibabaPuHuiTiM;
    color: #3cb1fb;
    line-height: 18rpx;
  }
  .item-unit {
    font-size: 10rpx;
    font-family: AlibabaPuHuiTi-Regular, AlibabaPuHuiTi;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.6);
    line-height: 18rpx;
    bottom: 0;
  }
}
.erc-line {
  width: 2px;
  height: 160rpx;
  margin-top: 30rpx;
  background: linear-gradient(180deg, rgba(60, 177, 251, 0) 0%, #3cb1fb 50%, rgba(60, 177, 251, 0) 100%);
}
.erc-item-box {
  width: 100%;
}
.erc-item {
  text-align: center;
  .erc-item-name {
    font-size: 14rpx;
    font-family: AlibabaPuHuiTi-Regular, AlibabaPuHuiTi;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.9);
    line-height: 18rpx;
    margin-bottom: 16rpx;
  }
}
.hse-item-name {
  font-size: 14rpx;
  font-family: AlibabaPuHuiTi-Regular, AlibabaPuHuiTi;
  font-weight: 400;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
}
.hse-item-num {
  width: 56rpx;
  height: 50rpx;
  background-image: url("/ifp-web-static/image/all/leadScreenNew/hse.png");
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 100% 100%;
  margin: 0 auto;
  margin-top: 6rpx;
  padding-top: 4rpx;
  text-align: center;
  span {
    font-size: 20rpx;
    font-family: AlibabaPuHuiTiM;
    color: #f5ba18;
    line-height: 27rpx;
    text-shadow: 0px 5rpx 9rpx #fff2cd;
    background: linear-gradient(180deg, #fff4d7 0%, #f5ba18 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
}
.nh-header {
  padding-left: 13rpx;
  margin-bottom: 4rpx;
  .mr-45 {
    margin-right: 45rpx;
  }
}
.zbm,
.nh {
  width: 46rpx;
  height: 41rpx;
  flex-shrink: 0;
  margin-right: 7rpx;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 100% 100%;
}
.flex {
  display: flex;
  align-items: center;
}
.zbm {
  background-image: url("/ifp-web-static/image/all/leadScreenNew/zbm.png");
}
.nh {
  background-image: url("/ifp-web-static/image/all/leadScreenNew/nh.png");
}
.jk-text {
  font-size: 14rpx;
  font-family: AlibabaPuHuiTiM;
  color: rgba(255, 255, 255, 0.9);
  line-height: 24rpx;
}
.jk-num {
  font-size: 24rpx;
  font-family: DOUYUFont;
  color: #3cb1fb;
  line-height: 24rpx;
}
.jk-unit {
  font-size: 14rpx;
  font-family: AlibabaPuHuiTiM;
  color: rgba(255, 255, 255, 0.9);
  line-height: 24rpx;
  bottom: 0;
}
</style>
